package com.lfg.message.delay.message.demo.delay.dl;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lfg
 * @version v1.0
 */
@Configuration
public class RabbitMqConfig1 {
    /**
     * 流程：
     * 1.消费者:重发队列跟 重发路由绑定
     * 2.死信交换机 死信路由不绑定消费者
     * 3.死信消息找不到消费者，有效时间到，自动转到重发队列
     * 4.重发队列有消费者，消费成功
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 死信交换机
     */
    private String dlExchange = "dead-letter-exchange-name";
    /**
     * 死信 路由key
     */
    private String dlRoutingKey = "dead-letter-routing-key-name";
    /**
     * 死信队列
     */
    private String dlQueue = "dead-letter-queue-name";
    /**
     * 重发路由key
     */
    private String reRoutingKey = "routing-key-name";
    /**
     * 重发队列
     */
    private String reQueue = "queue-name";


    /**
     * 声明死信交换机
     */
    @Bean("dlExchange")
    public Exchange dlExchange() {
        return ExchangeBuilder.directExchange(dlExchange).durable(true).build();
    }

    /**
     * 声明死信队列，指定死信交换机，死信路由
     */
    @Bean("dlQueue")
    public Queue dlQueue() {
        Map<String, Object> args = new HashMap<>(4);
        //指定交换机为死信交换机
        args.put("x-dead-letter-exchange", dlExchange);
        //指定路由为死信路由，值为重发路由
        args.put("x-dead-letter-routing-key", reRoutingKey);
        return QueueBuilder.durable(dlQueue).withArguments(args).build();
    }

    /**
     * 声明重发队列
     */
    @Bean("reQueue")
    public Queue reQueue() {
        return QueueBuilder.durable(reQueue).build();
    }

    /**
     * 死信队列绑定 死信交换机 死信路由
     */
    @Bean
    public Binding deadLetterPushBinding() {
        return new Binding(dlQueue, Binding.DestinationType.QUEUE, dlExchange, dlRoutingKey, null);
    }

    /**
     * 重发队列 绑定死信交换机 死信路由
     */
    @Bean
    public Binding redirectPushBinding() {
        return new Binding(reQueue, Binding.DestinationType.QUEUE, dlExchange, reRoutingKey, null);
    }

}
